package br.ufpe.cin.msc.jrsj2.recommender.algorithm.newuser;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import br.ufpe.cin.msc.jrsj2.recommender.persistence.dao.DAOFactory;
import br.ufpe.cin.msc.jrsj2.recommender.persistence.dao.ProfileDAO;
import br.ufpe.cin.msc.jrsj2.recommender.persistence.domain.Program;

public class PopularityStrategy extends NewUserStrategy {

	@Override
	public List<Program> getItens(List<Program> set, int size) {
		Map<Program, Integer> popularPrograms = new HashMap<Program, Integer>();
		ProfileDAO profileDAO = DAOFactory.getDAOFactory().getProfileDAO();
		int i = 1;

		for (Program program : set) {
			popularPrograms.put(program, profileDAO.countRating(program));
			if (i++ == size)
				break;
		}

		if (popularPrograms.size() > 1) {
			List<Entry<Program, Integer>> list = new ArrayList<Map.Entry<Program, Integer>>(
					popularPrograms.entrySet());

			Collections.sort(list, new Comparator<Entry<Program, Integer>>() {
				@Override
				public int compare(Entry<Program, Integer> o1,
						Entry<Program, Integer> o2) {
					return o1.getValue().compareTo(o2.getValue());
				}
			});

			popularPrograms.clear();

			for (Entry<Program, Integer> entry : list)
				popularPrograms.put(entry.getKey(), entry.getValue());
		}

		return new ArrayList<Program>(popularPrograms.keySet());
	}
}
